package com.cunzhang.server.interceptor;

import com.cunzhang.common.constants.JwtClaimsConstant;
import com.cunzhang.common.contexts.BaseContext;
import com.cunzhang.common.properties.JwtProperties;
import com.cunzhang.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtTokenAdminInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果请求的不是动态方法
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        //获取empid存入线程上下文
        String token = request.getHeader(jwtProperties.getAdminTokenName());
        try{
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
            if(empId != null){
                BaseContext.setCurrentId(empId);
                return true;
            }

            return false;
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(401);
            return false;
        }

    }
}
